package com.yuehuanghun.admin.core.controller.system;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.yuehuanghun.admin.core.config.UserConstants;
import com.yuehuanghun.admin.core.config.util.DeptUtils;
import com.yuehuanghun.admin.core.domain.SysDept;
import com.yuehuanghun.admin.core.domain.vo.TreeSelect;
import com.yuehuanghun.admin.core.service.ISysDeptService;
import com.yuehuanghun.framework.annotation.Log;
import com.yuehuanghun.framework.annotation.Log.BusinessType;
import com.yuehuanghun.framework.exception.ValidateException;
import com.yuehuanghun.framework.util.Kv;
import com.yuehuanghun.framework.util.StringUtils;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckPermission;

/**
 * 部门信息
 * 
 * @author yadmin
 */
@RestController
@RequestMapping("/system/dept")
@SaCheckLogin
public class SysDeptController {
	@Autowired
	private ISysDeptService deptService;

	/**
	 * 获取部门列表
	 */
	@GetMapping("/list")
	@SaCheckPermission("system:dept:list")
	public List<SysDept> list(SysDept dept) {
		return deptService.getDeptList(dept);
	}

	/**
	 * 查询部门列表（排除节点）
	 */
	@GetMapping("/list/exclude/{deptId}")
	@SaCheckPermission("system:dept:list")
	public List<SysDept> excludeChild(@PathVariable(value = "deptId", required = false) Long deptId) {
		List<SysDept> depts = deptService.getDeptList(new SysDept());
		Iterator<SysDept> it = depts.iterator();
		String deptIdQuoted = ":" + deptId + ":";
		while (it.hasNext()) {
			SysDept d = (SysDept) it.next();
			if (d.getDeptId().intValue() == deptId
					|| d.getAncestors().contains(deptIdQuoted)) {
				it.remove();
			}
		}
		return depts;
	}

	/**
	 * 根据部门编号获取详细信息
	 */
	@GetMapping(value = "/{deptId}")
	@SaCheckPermission("system:dept:query")
	public SysDept getInfo(@PathVariable Long deptId) {
		return deptService.getById(deptId).orElse(null);
	}

	/**
	 * 获取部门下拉树列表
	 */
	@GetMapping("/treeselect")
	public List<TreeSelect> treeselect(SysDept dept) {
		List<SysDept> depts = deptService.getDeptList(dept);
		return deptService.buildDeptTreeSelect(depts);
	}

	/**
	 * 加载对应角色部门列表树
	 */
	@SuppressWarnings("rawtypes")
	@GetMapping(value = "/roleDeptTreeselect/{roleId}")
	public Map roleDeptTreeselect(@PathVariable("roleId") Long roleId) {
		List<SysDept> depts = deptService.getDeptList(new SysDept());
		return Kv.by("checkedKeys", deptService.getDeptListByRoleId(roleId)).set("depts", deptService.buildDeptTreeSelect(depts));
	}

	/**
	 * 新增部门
	 */
	@Log(title = "部门管理", businessType = BusinessType.INSERT)
	@PostMapping
	@SaCheckPermission("system:dept:add")
	public void add(@Validated @RequestBody SysDept dept) {
		if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept))) {
			throw new ValidateException("新增部门'" + dept.getDeptName() + "'失败，部门名称已存在");
		}
		deptService.insertDept(dept);
		DeptUtils.removeCache(dept.getDeptId());
	}

	/**
	 * 修改部门
	 */
	@Log(title = "部门管理", businessType = BusinessType.UPDATE)
	@PutMapping
	@SaCheckPermission("system:dept:edit")
	public void edit(@Validated @RequestBody SysDept dept) {
		if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept))) {
			throw new ValidateException("修改部门'" + dept.getDeptName() + "'失败，部门名称已存在");
		} else if (dept.getParentId().equals(dept.getDeptId())) {
			throw new ValidateException("修改部门'" + dept.getDeptName() + "'失败，上级部门不能是自己");
		} else if (StringUtils.equals(UserConstants.DEPT_DISABLE, dept.getStatus())
				&& deptService.getNormalChildrenDeptById(dept.getDeptId()) > 0) {
			throw new ValidateException("该部门包含未停用的子部门！");
		}
		deptService.updateDept(dept);
		DeptUtils.removeCache(dept.getDeptId());
	}

	/**
	 * 删除部门
	 */
	@Log(title = "部门管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{deptId}")
	@SaCheckPermission("system:dept:remove")
	public void remove(@PathVariable Long deptId) {
		if (deptService.hasChildByDeptId(deptId)) {
			throw new ValidateException("存在下级部门,不允许删除");
		}
		if (deptService.checkDeptExistUser(deptId)) {
			throw new ValidateException("部门存在用户,不允许删除");
		}
		DeptUtils.removeCache(deptId);
		deptService.deleteDeptById(deptId);
	}
}
